package org.chene.elastic.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.chene.elastic.client.HttpConnectionManager;
import org.elasticsearch.common.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Service
public class SearchService {
	private static final String QUERY_URL_PREFIX = "/_sql?sql=";

	@Autowired
	private HttpConnectionManager httpConnectionManager;

	public <T> T one(String index, Class<T> clazz, String esql) throws Exception {
		List<T> list = list(index, clazz, esql);
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		return list.get(0);
	}

	public <T> List<T> list(String index, Class<T> clazz, String esql) {
		try {
			esql = URLEncoder.encode(esql, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String resultString = httpConnectionManager.get(QUERY_URL_PREFIX + esql);
		if (StringUtils.isBlank(resultString)) {
			return null;
		}

		JSONObject resultObject = JSON.parseObject(resultString);
		JSONArray hits = resultObject.getJSONObject("hits").getJSONArray("hits");
		List<T> result = new ArrayList<T>(hits.size());
		for (int i = 0; i < hits.size(); i++) {
			result.add(JSONObject.toJavaObject(hits.getJSONObject(i).getJSONObject("_source"), clazz));
		}

		return result;
	}
}
